package com.tongbo.mobilesafe.engine;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;

import com.tongbo.mobilesafe.domain.ContactInfo;

public class ContactInfoService {
	private Context context;
	
	public ContactInfoService(Context context) {
		this.context = context;
	}

	public List<ContactInfo> getContactInfos(){
		System.out.println("===============");
		ContentResolver resolver = context.getContentResolver();
		//1.获取联系人的id
		//2.根据联系人的id获取联系人的名字
		//3.根据联系人的id 数据type 获取到对应的数据(电话，email等)
		List<ContactInfo> contactInfos = new ArrayList<ContactInfo>();
		ContactInfo contactInfo = null;
		Uri uri = Uri.parse("content://com.android.contacts/raw_contacts");
		Uri dataUri = Uri.parse("content://com.android.contacts/data");
		Cursor cursor = resolver.query(uri, null, null, null, null);
		while(cursor.moveToNext()){
			contactInfo = new ContactInfo();
			String id = cursor.getString(cursor.getColumnIndex("_id"));
			System.out.println("联系人id:"+id);
			String name = cursor.getString(cursor.getColumnIndex("display_name"));
			contactInfo.setName(name);
			System.out.println("联系人姓名:"+name);
			Cursor dataCursor = resolver.query(dataUri, null, "raw_contact_id=?", new String[]{id}, null);
			while(dataCursor.moveToNext()){
				//mimetype
				String type = dataCursor.getString(dataCursor.getColumnIndex("mimetype"));
				if("vnd.android.cursor.item/phone_v2".equals(type)){
					String number = dataCursor.getString(dataCursor.getColumnIndex("data1"));
					contactInfo.setPhone(number);
				}
			}
			dataCursor.close();
			contactInfos.add(contactInfo);
			contactInfo = null;
		}
		cursor.close();
		return contactInfos;
	}
}